package com.example.portlocalforward.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.portlocalforward.controller.model.PortLocalForwardResponse;
import com.example.portlocalforward.entity.PortLocalForward;

/**
 * 端口本地转发数据访问层
 * 
 * @author Generated
 * @version 1.0.0
 */
@Repository
public interface PortLocalForwardRepository extends JpaRepository<PortLocalForward, Long> {

       /**
        * 查询所有端口本地转发（JOIN SSH隧道表获取名称）
        * 
        * @return 端口本地转发响应列表
        */
       @Query("SELECT new com.example.portlocalforward.controller.model.PortLocalForwardResponse(" +
                     "t.id, t.name, t.sshTunnelId, h.name, h.host, h.port, h.username, h.password, t.localPort, t.remoteHost, t.remotePort, t.url, t.tags, 0, t.createdTime, t.updatedTime) "
                     +
                     "FROM PortLocalForward t " +
                     "LEFT JOIN SshTunnel h ON t.sshTunnelId = h.id")
       List<PortLocalForwardResponse> findAllWithSshTunnelName();

       /**
        * 根据ID列表查询端口本地转发（JOIN SSH隧道表获取名称）
        * 
        * @param ids 端口本地转发ID列表
        * @return 端口本地转发列表
        */
       @Query("SELECT new com.example.portlocalforward.controller.model.PortLocalForwardResponse("
                     + "t.id, t.name, t.sshTunnelId, h.name, h.host, h.port, h.username, h.password,"
                     + " t.localPort, t.remoteHost, t.remotePort, t.url, t.tags, 0, t.createdTime, t.updatedTime) "
                     + "FROM PortLocalForward t " +
                     "LEFT JOIN SshTunnel h ON t.sshTunnelId = h.id WHERE t.id IN :ids")
       List<PortLocalForwardResponse> findAllWithSshTunnelNameByIds(@Param("ids") List<Long> ids);

       /**
        * 查询重复的端口转发配置
        * 校验条件：sshTunnelId + remoteHost + remotePort + localPort 的组合不能重复
        * 
        * @param sshTunnelId SSH隧道ID
        * @param remoteHost  远程主机
        * @param remotePort  远程端口
        * @param localPort   本地端口
        * @return 重复的端口转发配置（如果存在）
        */
       @Query("SELECT t FROM PortLocalForward t WHERE " +
                     "t.sshTunnelId = :sshTunnelId AND " +
                     "t.remoteHost = :remoteHost AND " +
                     "t.remotePort = :remotePort AND " +
                     "t.localPort = :localPort")
       Optional<PortLocalForward> findBySshTunnelIdAndRemoteHostAndRemotePortAndLocalPort(
                     @Param("sshTunnelId") Long sshTunnelId,
                     @Param("remoteHost") String remoteHost,
                     @Param("remotePort") int remotePort,
                     @Param("localPort") int localPort);
}
